const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { FoodCategory, RecipeCategory } = require('../models');

/**
 * 获取分类列表
 * 支持type参数：food(食品分类)或recipe(食谱分类)
 */
const getCategories = catchAsync(async (req, res) => {
  const { type = 'food' } = req.query;
  let categories = [];

  if (type === 'food') {
    categories = await FoodCategory.find({ isDeleted: false, isActive: true })
      .sort({ order: 1, createdAt: -1 })
      .select('name description image order');
  } else if (type === 'recipe') {
    categories = await RecipeCategory.find({ isDeleted: false, isActive: true })
      .sort({ order: 1, createdAt: -1 })
      .select('name description icon order');
  } else {
    throw new ApiError(httpStatus.BAD_REQUEST, '不支持的分类类型');
  }

  res.send(categories);
});

/**
 * 获取单个分类
 */
const getCategory = catchAsync(async (req, res) => {
  const { type = 'food' } = req.query;
  const { categoryId } = req.params;
  let category;

  if (!categoryId) {
    throw new ApiError(httpStatus.BAD_REQUEST, '分类ID不能为空');
  }

  if (type === 'food') {
    category = await FoodCategory.findOne({ 
      _id: categoryId, 
      isDeleted: false 
    });
  } else if (type === 'recipe') {
    category = await RecipeCategory.findOne({ 
      _id: categoryId, 
      isDeleted: false 
    });
  } else {
    throw new ApiError(httpStatus.BAD_REQUEST, '不支持的分类类型');
  }

  if (!category) {
    throw new ApiError(httpStatus.NOT_FOUND, '分类不存在');
  }

  res.send(category);
});

module.exports = {
  getCategories,
  getCategory,
}; 